# -*- coding: utf-8 -*-

import logging
import time
from opentracing import Format
from jaeger_client import Config
import random

if __name__ == "__main__":
    log_level = logging.DEBUG
    logging.getLogger("").handlers = []
    #logging.basicConfig(format="%(asctime)s %(message)s", level=log_level)
    logging.getLogger("").disabled
    logging.getLogger("jaeger_tracing").disabled = True
    config = Config(
        config = {
            "sampler" : {
                "type" : "const",
                "param" : 1,
            },
            "local_agent" : {
                "reporting_host" : "127.0.0.1",
                "reporting_port" : "6831",
            },
            "logging" : True,
        },
        service_name = "python-jb-test5",
        validate = True,
    )
    # 获取opentracing.tracer
    tracer = config.initialize_tracer()

    for idx in range(0, 1):
        uid = random.randint(1000000000, 99999999999)
        
        span = tracer.start_span("TestSpan2")
        span.set_tag("uid", uid)
        span.log_kv({"uid": uid, "event" : "test msg", "life" : 42})
        span.finish()

        #https://opentracing.io/guides/java/inject-extract/
        # bin实际测试有bug，但是txt_map传输需要自己打包
        bin_span_ctx = bytearray()
        tt = tracer.inject(span_context = span.context, format = Format.BINARY, carrier = bin_span_ctx)
        print(bin_span_ctx)
        txt_span_ctx = {}
        tt = tracer.inject(span_context = span.context, format = Format.TEXT_MAP, carrier = txt_span_ctx)
        span_ctx = tracer.extract(format = Format.BINARY, carrier = bin_span_ctx)
        span2 = tracer.start_span("ChildSpan", child_of=span_ctx)
        #span2.parent_id =
        span2.set_tag("uid", uid)
        span2.log_kv({"uid": uid, "event" : "down blow"})

        
        span2.finish()

    #time.sleep(3)
    tracer.close()

    # get_role(  MY_ROLE MY_HOSTNUM